package hr.dario.fragments;

import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import hr.dario.fragments.LocationsActivity.LocDescActivity;
import hr.dario.fragments.data.DataBaseAdapter;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class LocationsFragment extends ListFragment{
		//implements LoaderManager.LoaderCallbacks<Cursor>{
	private static final int ACTIVITY_DESC = 0;
	private boolean mDualPane;
	private int mCurCheckPosition = 1;
	
	private DataBaseAdapter mDbHelper;
	
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		mDbHelper = new DataBaseAdapter(getActivity());
				
		fillData();

		View detailsFrame = getActivity().findViewById(R.id.loc_desc_fragment);
        mDualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE;
  
        if (savedInstanceState != null) {
            // Restore last state for checked position.
            mCurCheckPosition = savedInstanceState.getInt("curChoice", 1);
        }

        if (mDualPane) {
            // In dual-pane mode, the list view highlights the selected item.
            getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
            // Make sure our UI is in the correct state.
            showDetails(mCurCheckPosition);
        }

	}
	
	@Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("curChoice", mCurCheckPosition);
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
    	System.out.println(""+position);
    	showDetails(position+1);
    }

    void showDetails(int index) {
        mCurCheckPosition = index;

        if (mDualPane) {
            // We can display everything in-place with fragments, so update
            // the list to highlight the selected item and show the data.
            getListView().setItemChecked(index, true);

            // Check what fragment is currently shown, replace if needed.
            LocDescFragment details = (LocDescFragment)
                    getFragmentManager().findFragmentById(R.id.loc_desc_fragment);
            if (details == null || details.getShownIndex() != index) {
                // Make new fragment to show this selection.
                details = LocDescFragment.newInstance(index);

                // Execute a transaction, replacing any existing fragment
                // with this one inside the frame.
                FragmentTransaction ft = getFragmentManager().beginTransaction();
                ft.replace(R.id.loc_desc_fragment, details);
                ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                ft.commit();
            }

        } else {
            // Otherwise we need to launch a new activity to display
            // the dialog fragment with selected text.
            Intent intent = new Intent();
            intent.setClass(getActivity(), LocDescActivity.class);
            intent.putExtra("index", index);
            startActivityForResult(intent, ACTIVITY_DESC);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        fillData();
    }
    
	private void fillData() {
		// Get all of the rows from the database and create the item list
		mDbHelper.open();
		Cursor EventsCursor = mDbHelper
				.fetchAllInputs(DataBaseAdapter.DATABASE_TABLE_LOC);
		getActivity().startManagingCursor(EventsCursor);
		
		
		// Create an array to specify the fields we want to display in the list
		// (only TITLE)
		String[] from = new String[] { DataBaseAdapter.KEY_LOC_NAME,
				DataBaseAdapter.KEY_LOC_DESCRIPTION };

		// and an array of the fields we want to bind those fields to (in this
		// case just text1)
		int[] to = new int[] { R.id.text1, R.id.text2 };
        
		// Now create a simple cursor adapter and set it to display
		SimpleCursorAdapter locations = new SimpleCursorAdapter(getActivity(),
				R.layout.location_row, EventsCursor, from, to);
		setListAdapter(locations);
						
		mDbHelper.close();
		
	}
	/*
	@Override
	public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        // This is called when a new Loader needs to be created.  This
        // sample only has one Loader, so we don't care about the ID.
        // First, pick the base URI to use depending on whether we are
        // currently filtering.
        Uri baseUri;
        
            baseUri = People.CONTENT_URI;
            
        

        // Now create and return a CursorLoader that will take care of
        // creating a Cursor for the data being displayed.
        String select = "((" + PeopleColumns.DISPLAY_NAME + " NOTNULL) AND ("
                + PeopleColumns.DISPLAY_NAME + " != '' ))";
        return new CursorLoader(getActivity(), baseUri,
                CONTACTS_SUMMARY_PROJECTION, select, null,
                PeopleColumns.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
    }

    @Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        // Swap the new cursor in.  (The framework will take care of closing the
        // old cursor once we return.)
        locations.swapCursor(data);

        // The list should now be shown.
        if (isResumed()) {
            setListShown(true);
        } else {
            setListShownNoAnimation(true);
        }
    }

    @Override
	public void onLoaderReset(Loader<Cursor> loader) {
        // This is called when the last Cursor provided to onLoadFinished()
        // above is about to be closed.  We need to make sure we are no
        // longer using it.
        locations.swapCursor(null);
    }
*/	 		  	
}
